package com.echat.api.demo.servlet;

import com.echat.api.demo.info.bizdata.*;
import com.echat.api.demo.util.EChatAPIConfig;
import com.echat.api.demo.util.EChatAPIUtil;
import com.echat.api.demo.util.StringUtil;
import com.echat.api.demo.util.XMLUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * Created by EChat
 * 接收一洽业务数据的接口地址，如果在一洽接口配置中配置了业务系统接收的URL那么一洽会在业务数据产生时向此URL post业务数据
 * 1.将此接口的URL配置到一洽的API接口中
 * 2.在一洽的业务系统数据接收的URL配置中检测通过验证
 * 3.开始接收一洽的业务数据.
 */
public class EChatDataReceiver extends HttpServlet {

    /**
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     * 通过get请求来校验一洽业务数据接收的URL是否正常，在一洽收到success返回后认为，可正常向此地址POST一洽的业务数据
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String signature = req.getParameter("signature");
        String nonce = req.getParameter("nonce");
        String timeStamp = req.getParameter("timestamp");
        if(StringUtil.isNotEmpty(signature) && StringUtil.isNotEmpty(nonce) && StringUtil.isNotEmpty(timeStamp)) {
            try {
                boolean verify = EChatAPIUtil.verifyURL(nonce, timeStamp, signature);
                if (verify) {
                    resp.getWriter().print("success");
                    resp.getWriter().flush();
                    resp.getWriter().close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     * 接收来自一洽的业务数据
     * 目前可接收：登陆状态数据、对话数据、客户数据
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String dataType = req.getParameter("dataType");
        if (StringUtil.isEmpty(dataType)) {
            System.out.println("invalidate echat data");
            return;
        }
        String signature = req.getParameter("signature");
        String nonce = req.getParameter("nonce");
        String timeStamp = req.getParameter("timestamp");
        boolean verify = false;
        if (StringUtil.isNotEmpty(signature) && StringUtil.isNotEmpty(nonce) && StringUtil.isNotEmpty(timeStamp)) {
            try {
                verify = EChatAPIUtil.verifyURL(nonce, timeStamp, signature);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (!verify) {
            //如果校验签名不通过则不做任何处理，说明不是一洽再向此URL post数据
            return;
        }
        //获取post的信息
        StringBuffer bizData = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = req.getReader();
            while ((line = reader.readLine()) != null)
                bizData.append(line);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String xmlData = bizData.toString();
        if (EChatAPIConfig.encryptPostData) {
            if (StringUtil.isNotEmpty(xmlData)) {
                try {
                    xmlData = EChatAPIUtil.decryptPostBizData(xmlData);
                } catch (Exception e) {
                    //获取业务数据异常
                    e.printStackTrace();
                }
            }
        }
        xmlData.replaceAll("\\s","");
        xmlData = xmlData.replaceAll("\\n","");
        if (StringUtil.isEmpty(xmlData)) {
            System.out.println("获取一洽业务数据异常");
            return;
        }
        if (dataType.equals("companyStatus")) {
            //公司状态变更数据
            CompanyStatusChange companyStatusChange = (CompanyStatusChange) XMLUtil.toBean(xmlData, CompanyStatusChange.class);
            System.out.println("companyStatus :" + xmlData);
            //业务处理
        }else if (dataType.equals("skillStatus")) {
            //分组状态变更
            SkillStatusChange skillStatusChange = (SkillStatusChange) XMLUtil.toBean(xmlData, SkillStatusChange.class);
            System.out.println("skillStatus :" + xmlData);
        }else if (dataType.equals("staffStatus")) {
            //客服状态变更
            StaffStatusChange staffStatusChange = (StaffStatusChange) XMLUtil.toBean(xmlData, StaffStatusChange.class);
            System.out.println("staffStatus :" + xmlData);
        }else if (dataType.equals("chatStart")) {
            //对话开始
            ChatStartInfo chatStartInfo = (ChatStartInfo) XMLUtil.toBean(xmlData, ChatStartInfo.class);
            System.out.println("chatStart :" + xmlData);
        }else if (dataType.equals("chatEnd")) {
            //对话结束
            ChatEndInfo chatEndInfo = (ChatEndInfo) XMLUtil.toBean(xmlData, ChatEndInfo.class);
            System.out.println("chatEnd :" + xmlData);
        }else if(dataType.equals("chatSubject")) {
            //对话总结数据
            ChatSubjectInfo chatSubjectInfo = (ChatSubjectInfo) XMLUtil.toBean(xmlData, ChatSubjectInfo.class);
            System.out.println("chatSubject :" + xmlData);
        }else if(dataType.equals("chatScore")) {
            //访客评价数据
            ChatEvaluateInfo chatEvaluateInfo = (ChatEvaluateInfo) XMLUtil.toBean(xmlData, ChatEvaluateInfo.class);
            System.out.println("chatScore :" + xmlData);
        }else if (dataType.equals("crmStatus")) {
            //访客crm数据
            CrmInfo crmInfo = (CrmInfo) XMLUtil.toBean(xmlData, CrmInfo.class);
            System.out.println("crmStatus :" + xmlData);
        }


    }
}
